package com.handu.luna.boss.controller;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.validation.Valid;

import net.sf.json.JSONObject;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.handu.luna.core.domain.advertisement.AdPositionId;
import com.handu.luna.core.domain.advertisement.AdvertiseList;
import com.handu.luna.core.domain.search.AdvertiseSearch;
import com.handu.luna.core.domain.support.FileUploadSupport;
import com.handu.luna.core.domain.support.FileUploadSupport.ImageType;

@Controller
@RequestMapping("/advertisement/adsList/*")
public class AdvertiseListController extends BaseController{
	
	//点击搜索按钮
	@RequestMapping(value ="index",method = RequestMethod.POST)  //size = DEFAULT_PAGE_SIZE
	public BossModel index(AdvertiseSearch advertiseSearch,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE ,sort="id",direction= Direction.DESC) Pageable pageable)throws UnsupportedEncodingException{
		List<AdPositionId> lists = context.getAdPositionIdRepository().findAll();    
		    return createModel("/advertisement/adsList/index")
		    	.add("adPositionNames", lists)
				.add("advertiseSearch",advertiseSearch)
				.add("advertiseListPage",new AdvertiseList().findAll(advertiseSearch, pageable))
				.add("viewState", Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(advertiseSearch).toString().getBytes("UTF-8")));
				
	}
	
	
	//点击广告位，显示相应的广告

	@RequestMapping(value ="index/{id}",method = RequestMethod.GET)
	public BossModel index(@PathVariable long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE ,sort="id",direction= Direction.DESC) Pageable pageable)throws UnsupportedEncodingException{

		List<AdPositionId> lists = context.getAdPositionIdRepository().findAll();
        AdvertiseSearch advertiseSearch = new AdvertiseSearch();
        advertiseSearch.setAdPositionNameById(id +"");//因定义的AdPositionNameById 为string类型，所以得加个空字符串
    	if(id!=0){
    	
    		return createModel("/advertisement/adsList/index")
    				.add("adPositionNames", lists)
    				.add("advertiseSearch",advertiseSearch)
    				.add("advertiseListPage",new AdvertiseList().findAll(id, pageable))
    				.add("viewState", Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(advertiseSearch).toString().getBytes("UTF-8")));
    	}else{
		    return createModel("/advertisement/adsList/index")
				.add("adPositionNames", lists)
				.add("advertiseSearch",advertiseSearch)
				.add("advertiseListPage",new AdvertiseList().findAll(pageable))
				.add("viewState", Base64.getUrlEncoder().encodeToString(JSONObject.fromObject(advertiseSearch).toString().getBytes("UTF-8")));
    	}
		
	}
	
	//搜索 和列表 分页
	
	@RequestMapping(value = "index")  
	public BossModel index(String viewState,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE ,sort="id",direction= Direction.DESC) Pageable pageable)throws UnsupportedEncodingException {
        List<AdPositionId> lists = context.getAdPositionIdRepository().findAll();
		AdvertiseSearch advertiseSearch;
		if(viewState != null && !viewState.trim().equals("") && !viewState.equals("-1")){
		   //解析传递过来的查询json字符串
			advertiseSearch = (AdvertiseSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState),"UTF-8")), AdvertiseSearch.class);
           // AdvertiseList advertiseList = new AdvertiseList();
            
		    return createModel("/advertisement/adsList/index")
				.add("advertiseListPage",new AdvertiseList().findAll(advertiseSearch, pageable))
				.add("adPositionNames", lists)
				.add("advertiseSearch",advertiseSearch)
				.add("viewState", viewState);
	   }else{
		   advertiseSearch = new AdvertiseSearch();
		
		    return createModel("/advertisement/adsList/index")
				.add("advertiseListPage",new AdvertiseList().findAll(advertiseSearch, pageable))
				.add("adPositionNames", lists)
				.add("advertiseSearch",advertiseSearch)
				.add("viewState", "");
	   }
	}
	
	@RequestMapping(value = "add")
	public BossModel add(){ 
		List<AdPositionId> lists = context.getAdPositionIdRepository().findAll();
		
        AdvertiseList AdvertiseList = new AdvertiseList();
        AdvertiseList.setDisplayed(true);
        AdvertiseList.setSortOrder(100);
		
		return createModel("advertisement/adsList/save")
				.add("advertiseInfo", AdvertiseList)
				.add("adPositionNames",lists);
	}
	
	@RequestMapping(value = "edit/{id}")
	public BossModel edit(@PathVariable long id) {
		List<AdPositionId> lists = context.getAdPositionIdRepository().findAll();   
		return createModel("advertisement/adsList/save")
				.add("advertiseInfo",context.getAdvertiseListRepository().findOne(id))
				.add("adPositionNames", lists);
	}
	
	@RequestMapping(value = "delete")    
	public BossModel delete(String viewState,long id,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE ,sort="id",direction= Direction.DESC) Pageable pageable)throws UnsupportedEncodingException {
		
		 List<AdPositionId> lists = context.getAdPositionIdRepository().findAll();//获得所有的广告位名称
		// AdvertiseSearch advertiseSearch = new AdvertiseSearch();
		AdvertiseSearch advertiseSearch;
		if(viewState != null && !viewState.trim().equals("") && !viewState.equals("-1")){
			 //解析传递过来的查询json字符串
			advertiseSearch = (AdvertiseSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getUrlDecoder().decode(viewState),"UTF-8")), AdvertiseSearch.class);
			context.getAdvertiseListRepository().delete(id);
			return createModel("advertisement/adsList/adslist_table")  //局部刷新
					.add("advertiseListPage",new AdvertiseList().findAll(advertiseSearch, pageable))
					
					.add("viewState", viewState)
					.add("adPositionNames", lists)
			        .add("advertiseSearch",advertiseSearch);
		}else{
			advertiseSearch = new AdvertiseSearch();
			context.getAdvertiseListRepository().delete(id);
			return createModel("advertisement/adsList/adslist_table")  //局部刷新
					.add("advertiseListPage",new AdvertiseList().findAll(advertiseSearch, pageable))
					.add("viewState", "")
					.add("adPositionNames", lists)
			        .add("advertiseSearch",advertiseSearch);
		}
		
	}
	  
		
	@RequestMapping(value="save",method = RequestMethod.POST)
	@InitBinder(value={"advertiseName","mediaType","adPositionId","sortOrder","startDate","endDate","advertiseLink","advertiseImageUrl","displayed","description"})
	public BossModel save(@Valid final AdvertiseList advertiseList,final BindingResult bindingResult,RedirectAttributes redirectAttributes,
			@RequestParam("uploadfile") MultipartFile file){
		String message = "";
		List<AdPositionId> lists = context.getAdPositionIdRepository().findAll();

		if(bindingResult.hasErrors()){
			return createModel("advertisement/adsList/save").add("adPositionNames", lists);
		}
	
		int num = 0;
		int nullFileUrl = 0;
		int writePath = 0;
		if (!file.isEmpty() && "".equals(advertiseList.getAdvertiseImageUrl())) {
			String fileurl = saveFile(file);
			if(fileurl==null){
				nullFileUrl = 1;
			}else{
		    	advertiseList.setAdvertiseImageUrl(fileurl);
			}
			
		}else if(file.isEmpty() && !("".equals(advertiseList.getAdvertiseImageUrl()))){
			String url = advertiseList.getAdvertiseImageUrl();   //gif|jpg|jpeg|png
			if((url.startsWith("http://", 0) || url.startsWith("/", 0)) && (url.endsWith(".jpg") || url.endsWith(".gif") || url.endsWith(".jpeg") || url.endsWith(".png") )){
				advertiseList.setAdvertiseImageUrl(url);
			}else{
				writePath = 1;
			}
		}else if(!file.isEmpty() && advertiseList.getAdvertiseImageUrl()!=null){
			num=1;	
		}	
		
   	//当添加广告的时候，先判断  所属广告位  是否存在	
	  Long adPositionCheckById = context.getAdPositionIdRepository().count("id",advertiseList.getAdPositionId());

	  //判断传过来的参数  是否全部为空格
	 
	    String advertiseName = advertiseList.getAdvertiseName().trim();
	    long adPositionId = advertiseList.getAdPositionId();
	    String advertiseLink = advertiseList.getAdvertiseLink().trim();
	   
		if(adPositionCheckById==0){
			  message = "所添加广告位已被删除";
		}
		else if(num==1){
			 message = "上传图片地址发生了冲突，请选择其一";
		}
		/*else if((null==advertiseList.getId() || advertiseList.getId()==0) && (!advertiseName.isEmpty()) && nullFileUrl!=1 && writePath!=1 && adPositionId!=0 && !advertiseLink.isEmpty() && advertiseList.getMediaType()!=null && )
		{
			context.getAdvertiseListRepository().save(advertiseList);
			message = "添加" + advertiseList.getAdvertiseName() +"成功";
		}*/
		else if(advertiseName.isEmpty()){
			message = "文章标题不能为空！";		
		}else if(null == advertiseList.getMediaType()){
			message = "没有选择媒介类型！";
		}else if(adPositionId==0){
			message = "没有选择广告位！";
		}else if(null == advertiseList.getStartDate()){
			message = "开始时间不能为空！";
			
		}else if(null == advertiseList.getEndDate()){
			message = "结束时间不能为空！";
		}else if(advertiseLink.isEmpty()){
			message = "广告链接不能为空！";	
		}else if(nullFileUrl==1){
			message = "所上传文件类型不是图片";		
		}else if(writePath==1){
			message = "所填写的图片路径不合格！";
			
		}else if(null !=advertiseList.getId() && advertiseList.getId()!=0 && null !=advertiseList.getStartDate() && null !=advertiseList.getEndDate()){
		  
				if(advertiseList.getStartDate().compareTo(advertiseList.getEndDate()) !=-1){
					message = "开始时间必须小于结束时间！";
				}else{
					context.getAdvertiseListRepository().save(advertiseList);
					message = "修改" + advertiseList.getAdvertiseName() +"成功";
				}					
		}else{
			if(null !=advertiseList.getStartDate() && null !=advertiseList.getEndDate()){
				if(advertiseList.getStartDate().compareTo(advertiseList.getEndDate()) !=-1){
					message = "开始时间必须小于结束时间！";
				}else{
					context.getAdvertiseListRepository().save(advertiseList);
					message = "添加" + advertiseList.getAdvertiseName() +"成功";
				}
			}			
		}
		
		//context.getArticleListRepository().save(articleList);
		redirectAttributes.addFlashAttribute("message",message);
		return createModel("redirect:index");		
		
	}
	
	
	/***
	 * 保存文件
	 * @param file
	 * @return
	 */
	private @ResponseBody() String saveFile(MultipartFile file) {

        if (!file.isEmpty()) {
            try {
            	/*命名规则*/
            	String pic_type = file.getContentType();
            	String fileName;
            	Random random = new Random();
    			int x = random.nextInt(899999);
    			int randomValue = x+100000;
    			//alert("图片类型必须是.gif,jpeg,jpg,png中的一种");  
            	String file_ture_name = new Date().getTime()+randomValue+"_s";
            	if(pic_type.equals("image/jpg")){
            		fileName =   file_ture_name.concat(".jpg");
            	} else if (pic_type.equals("image/png")){
            		fileName = file_ture_name.concat(".png");
            	} else if(pic_type.equals("image/jpeg")){
            		fileName =  file_ture_name.concat(".jpeg");
            	} else if(pic_type.equals("image/gif")){
            		fileName = file_ture_name.concat(".gif");
            	} else	{ 
            		return null; //"You failed to upload " + file.getName() + " because the file type is not pictures";
            	}
            	
            	String returnMessage = FileUploadSupport.upload(file.getInputStream(), fileName, ImageType.ADVERTISES);
                return returnMessage;
            } catch (Exception e) {
                return "You failed to upload " + file.getName() + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + file.getName() + " because the file was empty.";
        }
	}
	
	

}
